package com.fast.controller.thread;


import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.api.R;
import com.fast.controller.thread.task.FutureTestTask;
import com.fast.controller.thread.task.TestTask;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.*;

/**
 * @author hujw
 * @since 2021/12/20
 */
@RestController
@Api(tags = "线程测试")
@RequestMapping("/thread")
public class ThreadController extends ApiController {
    @Autowired
    @Qualifier("voidThreadPool")
    ThreadPoolExecutor baseThreadPool;

    @Autowired
    @Qualifier("futureCompletionService")
//    @Resource(name = "futureCompletionService")//按名字注入，相当于@Autowired和@Qualifier("futureCompletionService")一起使用
    CompletionService<R> completionService;

    @Autowired
    private ApplicationContext applicationContext;

    @ApiOperation("线程池-无返回值-常用于定时任务")
    @GetMapping("test1")
    public R test1() {
        for (int i = 0; i < 10; i++) {
            TestTask testTask = applicationContext.getBean(TestTask.class);
            testTask.setBusinessId(Long.valueOf(i));
            baseThreadPool.submit(testTask);
        }
        return success("执行成功");
    }

    @ApiOperation("线程池-有返回值-用于拆分for循环调用外系统有返回值的场景")
    @GetMapping("test2")
    public R test2(Integer num) throws InterruptedException, ExecutionException {
        for (int i = 0; i < num; i++) {
            FutureTestTask futureTestTask = applicationContext.getBean(FutureTestTask.class);
            futureTestTask.setId(i);
            completionService.submit(futureTestTask);
        }

//        for (int i = 0; i < num; i++) {
//            //取的时候是无序的
//            Future<R> future = completionService.poll(3, TimeUnit.SECONDS);
//            System.out.println("future = " + future.get().getData());
//        }
        return success("执行成功");
    }
}
